package cn.melonlib.authentication.comp.service;

import cn.hutool.core.codec.Base64;
import cn.melonlib.authentication.model.entity.HttpAccount;
import cn.melonlib.cores.jpa.comp.Dao;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import org.apache.commons.lang3.StringUtils;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class HttpAccountLoginService {

    private static final Pattern authRegex=Pattern.compile("^.*Basic (.+)$");

    private static final Pattern userRegex=Pattern.compile("^(.+):(.+)$");

    @Resource
    private Dao dao;

    public boolean checkAuth(String authInfo){
        if(StringUtils.isBlank(authInfo)){
            return false;
        }
        try {
            Matcher m=authRegex.matcher(authInfo);
            if(m.matches()){
                Matcher up=userRegex.matcher(new String(Base64.decode(m.group(1)), StandardCharsets.UTF_8));
                if(up.matches()){
                    String user=up.group(1);
                    String password=up.group(2);
                    @Language("HQL") String query="from HttpAccount where loginName=?1 and password=?2";
                    return dao.<List<HttpAccount>,DefaultQuery>search(new DefaultQuery(query, List.of(user,password))).getResult().size()>0;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }catch (Exception e){
            return false;
        }
    }
}
